package org.example.service.impl;


import org.example.domain.R;
import org.example.domain.Setmeal;
import org.example.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;


import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class MailService {
    @Autowired
    SetmealService setmealService;

    @Autowired
    private JavaMailSender mailSender; // JavaMailSender对象用于发送邮件
    // RedisTemplate对象用于保存验证码

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;




    //生成随机验证码通过自己配置的邮箱发送到目标邮箱
    public R<String> sendMail(String email) {
        // 在redis中生成6位随机验证码，过期时间为10分钟
        MimeMessage message = mailSender.createMimeMessage();
        String code = String.valueOf(new Random().nextInt(899999) + 100000);
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        ops.set(email, code, 10, TimeUnit.MINUTES);
        // 创建一个MimeMessage对象

        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom("your_email@qq.com"); // 发件人邮箱
            helper.setTo(email); // 收件人邮箱
            helper.setSubject("验证码"); // 邮件主题
            helper.setText("您的验证码为：" + code); // 邮件内容
 
            mailSender.send(message); // 发送邮件
            return R.success("验证码已发送");
        } catch (MessagingException e) {
            e.printStackTrace();
            return R.error("发送失败，请检查邮箱地址是否正确");
        }
    }
 
    public R<String> verifyCode(String email, String code) {
        Object o = redisTemplate.opsForValue().get(email);
        String savedCode=(String) o;
        if (savedCode == null || !savedCode.equals(code)) {
            return R.error("验证码错误");
        }
        return R.success("成功");
    }
}

